package com.link.base.ext.autocfg.service;

import com.link.base.user.model.CoreUser;
import com.link.core.basic.dao.mapper.BasicMapper;
import com.link.core.basic.service.BasicServiceException;
import com.link.core.basic.service.BasicServiceImpl;
import com.link.core.basic.service.ServiceException;
import com.link.core.util.UserUtil;
import com.link.base.ext.autocfg.dao.mybatis.mapper.AutoCfgMapper;
import com.link.base.ext.autocfg.model.AutoCfg;
import com.link.base.ext.autocfg.model.AutoCfgItem;
import com.link.base.ext.autocfg.model.AutoCfgItemSub;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;


@Service
public class AutoCfgServiceImpl extends BasicServiceImpl<AutoCfg> implements AutoCfgService {

    @Resource
    private AutoCfgMapper autoCfgMapper;
    @Resource
    private AutoCfgItemService autoCfgItemService;
    @Resource
    private AutoCfgItemSubService autoCfgItemSubService;

    @Override
    public BasicMapper<AutoCfg> getBasicMapper() {
        return autoCfgMapper;
    }

    @Override
    public void beforUpsert(AutoCfg entity) throws Exception {
        CoreUser user = UserUtil.getUser();
        if (user == null) {
            throw new ServiceException("AUTOCFG-007");
        }
    }

    @Override
    public void beforDelete(AutoCfg entity) throws Exception {
        beforUpsert(entity);
    }

    @Transactional(rollbackFor = BasicServiceException.class)
    @Override
    public void deepCopy(AutoCfg record) throws Exception {


    }

    @Override
    public void insert(AutoCfg record) throws Exception {
        Long basicId = record.getBasicId();

        super.insert(record);

        if (null != basicId) {
            AutoCfgItem itemExample = new AutoCfgItem();
            itemExample.setHeadId(basicId);
            itemExample.setPageFlag(false);
            itemExample.setLoginCorpId(UserUtil.getUser().getCorpid());
            itemExample.setJoinSubFlag(true);
            List<AutoCfgItem> itemList = autoCfgItemService.queryByExamplePage(itemExample); //只查询相同corp的配置行

            Long headId = record.getId();
            for (AutoCfgItem item : itemList) {
                item.setHeadId(headId);
                item.setId(null);

                autoCfgItemService.insert(item);

                if (item.getSubList() != null && item.getSubList().size() > 0) {
                    for (AutoCfgItemSub sub : item.getSubList()) {
                        sub.setId(null);
                        sub.setParentId(item.getId());
                        autoCfgItemSubService.insert(sub);
                    }
                }
            }
        }

    }
}
